package service

import (
	"encoding/json"
	"fmt"
	"k8s-service/db"
	"k8s-service/models"
	"log"
	"strings"
)

type ModelConfigService struct {
	db *db.ModelConfigDB
}

// NewModelConfigService 创建ModelConfigService实例
func NewModelConfigService(dbPath string) (*ModelConfigService, error) {
	modelConfigDB, err := db.NewModelConfigDB(dbPath)
	if err != nil {
		return nil, err
	}
	return &ModelConfigService{db: modelConfigDB}, nil
}

// Close 关闭服务
func (s *ModelConfigService) Close() error {
	return s.db.Close()
}

// CreateModelConfig 创建模型配置
func (s *ModelConfigService) CreateModelConfig(req *models.CreateModelConfigRequest) (*models.ModelConfig, error) {
	// 验证请求参数
	if err := s.validateCreateRequest(req); err != nil {
		return nil, err
	}

	// 转换为数据库模型
	config := &models.ModelConfig{
		ModelPath:      req.ModelPath,
		RequestHeaders: req.RequestHeaders,
		VendorCN:       req.VendorCN,
		VendorEN:       req.VendorEN,
		VendorImg:      req.VendorImg,
		ModelName:      req.ModelName,
		ModelType:      req.ModelType,
		Enabled:        req.Enabled,
	}

	// 创建配置
	err := s.db.CreateModelConfig(config)
	if err != nil {
		log.Printf("创建模型配置失败: %v", err)
		return nil, fmt.Errorf("创建模型配置失败")
	}

	log.Printf("成功创建模型配置: %s - %s", config.VendorCN, config.ModelType)
	return config, nil
}

// GetModelConfigByID 根据ID获取模型配置
func (s *ModelConfigService) GetModelConfigByID(id int) (*models.ModelConfig, error) {
	if id <= 0 {
		return nil, fmt.Errorf("无效的ID")
	}

	config, err := s.db.GetModelConfigByID(id)
	if err != nil {
		log.Printf("获取模型配置失败，ID: %d, 错误: %v", id, err)
		return nil, err
	}

	return config, nil
}

// UpdateModelConfig 更新模型配置
func (s *ModelConfigService) UpdateModelConfig(id int, req *models.UpdateModelConfigRequest) (*models.ModelConfig, error) {
	if id <= 0 {
		return nil, fmt.Errorf("无效的ID")
	}

	// 获取原有配置
	existingConfig, err := s.db.GetModelConfigByID(id)
	if err != nil {
		return nil, err
	}

	// 更新字段（只更新非空字段）
	if req.ModelPath != "" {
		existingConfig.ModelPath = req.ModelPath
	}
	if req.RequestHeaders != "" {
		existingConfig.RequestHeaders = req.RequestHeaders
	}
	if req.VendorCN != "" {
		existingConfig.VendorCN = req.VendorCN
	}
	if req.VendorEN != "" {
		existingConfig.VendorEN = req.VendorEN
	}
	if req.VendorImg != nil {
		existingConfig.VendorImg = req.VendorImg
	}
	if req.ModelName != nil {
		existingConfig.ModelName = req.ModelName
	}
	if req.ModelType != "" {
		// 验证模型类型
		if !s.isValidModelType(req.ModelType) {
			return nil, fmt.Errorf("无效的模型类型: %s", req.ModelType)
		}
		existingConfig.ModelType = req.ModelType
	}
	if req.Enabled != nil {
		existingConfig.Enabled = *req.Enabled
	}

	// 更新数据库
	err = s.db.UpdateModelConfig(id, existingConfig)
	if err != nil {
		log.Printf("更新模型配置失败，ID: %d, 错误: %v", id, err)
		return nil, fmt.Errorf("更新模型配置失败")
	}

	log.Printf("成功更新模型配置: ID=%d, %s - %s", id, existingConfig.VendorCN, existingConfig.ModelType)
	return existingConfig, nil
}

// DeleteModelConfig 删除模型配置
func (s *ModelConfigService) DeleteModelConfig(id int) error {
	if id <= 0 {
		return fmt.Errorf("无效的ID")
	}

	err := s.db.DeleteModelConfig(id)
	if err != nil {
		log.Printf("删除模型配置失败，ID: %d, 错误: %v", id, err)
		return err
	}

	log.Printf("成功删除模型配置，ID: %d", id)
	return nil
}

// ListModelConfigs 获取模型配置列表
func (s *ModelConfigService) ListModelConfigs(page, size int, modelType string, enabled *int) (*models.ModelConfigListResponse, error) {
	// 验证分页参数
	if page <= 0 {
		page = 1
	}
	if size <= 0 || size > 100 {
		size = 10
	}

	// 验证模型类型
	if modelType != "" && !s.isValidModelType(modelType) {
		return nil, fmt.Errorf("无效的模型类型: %s", modelType)
	}

	configs, total, err := s.db.ListModelConfigs(page, size, modelType, enabled)
	if err != nil {
		log.Printf("获取模型配置列表失败: %v", err)
		return nil, fmt.Errorf("获取模型配置列表失败")
	}

	return &models.ModelConfigListResponse{
		Total: total,
		List:  configs,
		Page:  page,
		Size:  size,
	}, nil
}

// GetEnabledModelConfigs 获取所有启用的模型配置
func (s *ModelConfigService) GetEnabledModelConfigs() ([]models.ModelConfig, error) {
	configs, err := s.db.GetEnabledModelConfigs()
	if err != nil {
		log.Printf("获取启用的模型配置失败: %v", err)
		return nil, fmt.Errorf("获取启用的模型配置失败")
	}

	log.Printf("获取到 %d 个启用的模型配置", len(configs))
	return configs, nil
}

// ToggleModelConfigStatus 切换模型配置启用状态
func (s *ModelConfigService) ToggleModelConfigStatus(id int) (*models.ModelConfig, error) {
	config, err := s.db.GetModelConfigByID(id)
	if err != nil {
		return nil, err
	}

	// 切换状态
	if config.Enabled == 1 {
		config.Enabled = 0
	} else {
		config.Enabled = 1
	}

	// 更新数据库
	err = s.db.UpdateModelConfig(id, config)
	if err != nil {
		return nil, err
	}

	statusStr := "禁用"
	if config.Enabled == 1 {
		statusStr = "启用"
	}
	log.Printf("成功%s模型配置，ID: %d", statusStr, id)
	return config, nil
}

// validateCreateRequest 验证创建请求
func (s *ModelConfigService) validateCreateRequest(req *models.CreateModelConfigRequest) error {
	if strings.TrimSpace(req.ModelPath) == "" {
		return fmt.Errorf("模型路径不能为空")
	}
	if strings.TrimSpace(req.VendorCN) == "" {
		return fmt.Errorf("供应商中文名不能为空")
	}
	if strings.TrimSpace(req.VendorEN) == "" {
		return fmt.Errorf("供应商英文名不能为空")
	}
	if !s.isValidModelType(req.ModelType) {
		return fmt.Errorf("无效的模型类型: %s", req.ModelType)
	}

	// 验证请求头格式（如果提供）
	if req.RequestHeaders != "" {
		if !s.isValidJSON(req.RequestHeaders) {
			return fmt.Errorf("请求头必须是有效的JSON格式")
		}
	}

	// 验证启用状态
	if req.Enabled != 0 && req.Enabled != 1 {
		return fmt.Errorf("启用状态只能是0或1")
	}

	return nil
}

// isValidModelType 验证模型类型
func (s *ModelConfigService) isValidModelType(modelType string) bool {
	validTypes := []string{"llm", "embedding", "reranker"}
	for _, validType := range validTypes {
		if modelType == validType {
			return true
		}
	}
	return false
}

// isValidJSON 验证是否为有效JSON
func (s *ModelConfigService) isValidJSON(str string) bool {
	var js json.RawMessage
	return json.Unmarshal([]byte(str), &js) == nil
}
